package com.haier.npt.filter.authentication;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haier.npt.authention.authc.AuthenticationInfo;
import com.haier.npt.filter.AbstractProcessingFilter;
import com.haier.npt.sso.utils.AuthorizationUtil;
import com.netflix.zuul.context.RequestContext;

/**
 * @Description: 
 * @author: lixu
 * @date:   2018年7月12日 下午3:13:08   
 */
public abstract class AbstractAuthenticationFilter extends AbstractProcessingFilter{

	@Override
	public boolean shouldFilter(){
		RequestContext ctx = RequestContext.getCurrentContext();
		return !ctx.getBoolean("ignore");
	}
	
	@Override
	public Object run(){
		try{
			HttpServletRequest request = super.getCtx().getRequest();
			HttpServletResponse response = super.getCtx().getResponse();
			/**
			 * 获取传递的token
			 */
			String token = AuthorizationUtil.getRequestAccessToken(request);
			
			AuthenticationInfo authResult = this.doAuthenticate(token, request, response);
			if (authResult == null) {
				// 认证失败
				onLoginFailure(super.getCtx());
			} else {
				// 认证成功
				successfulAuthentication(authResult);
			}
		}
		catch (Exception ex) {
			super.processZuulException(ex);
	    }
		
		return null;
	}
	
	/**
	 * 认证方法 ,返回不为空的对象， 说明认证成功
	 * @param request
	 * @param response
	 * @return
	 */
	abstract AuthenticationInfo  doAuthenticate(String token ,HttpServletRequest request ,HttpServletResponse response) ;
	
	/**
	 * 认证成功
	 * @param request
	 * @param response
	 * @param Authentication
	 * @throws IOException
	 * @throws ServletException
	 */
	@SuppressWarnings("unchecked")
	protected void successfulAuthentication(AuthenticationInfo authentication)  {
		super.setToken(authentication.getToken());
		Map<String,Object> haierUser = (Map<String, Object>) authentication.getPrincipal() ;
		String userid = (String)haierUser.get("id") ; 
		super.setUserid(Long.valueOf(userid));
	}
}
